"""
路由是蓝图和视图函数之间的抽象层
用于分离接口，粒度比蓝图更细

Author: wenbin
Create: 2024-08-16
"""
from dataclasses import dataclass, field

from flask import Blueprint
from injector import inject


@inject
@dataclass
class Router:
    """路由"""

    root: str
    view_funcs: list = field(default_factory=list)

    def bind(self, rule: str = "", **options):
        """
        给视图函数绑定路由规则

        :param rule: 路由规则
        :param options: 选项
        """

        def decorator(func):
            self.view_funcs.append((func, rule, options))
            return func

        return decorator

    def register(self, blueprint: Blueprint, instance: object = None) -> None:
        """
        注册路由

        :param blueprint: 蓝图实例
        :param instance: 视图函数的实例
        """

        for func, rule, options in self.view_funcs:
            endpoint = options.pop("endpoint", func.__name__)
            if instance:
                func = func.__get__(instance, type(instance))
            blueprint.add_url_rule(_format_rule(self.root, rule), endpoint, func, **options)


def _format_rule(root: str, rule: str) -> str:
    """
    格式化路由规则

    :param root: 根路由
    :param rule: 路由
    :return: 路由
    """
    if not root.startswith("/"):
        root = "/" + root
    if not rule.startswith("/"):
        rule = "/" + rule
    return root + rule
